import { ISceneManager } from "../ADCore/Interfaces/IGameManager";
import { LayerEnum } from "../ADCore/Interfaces/IEnum";
import { IElmentRoot } from "../ADCore/Interfaces/IRole";
import { IDictionary, IEventHandler } from "../ADCore/Interfaces/IUtils";
import LambdaExpression from "../ADCore/Utils/LambdaExpression";

export default class SceneManager implements ISceneManager {
  beforeUpdate: IEventHandler;
  updated: IEventHandler;
  getCount(): number;
  getCount(layer?: LayerEnum): number {
    if (layer) {
      return LambdaExpression.count(this.elementsList, (mm) => {
        return mm.layer == layer;
      });
    } else {
      return this.elementsList.length;
    }
  }
  private stage: Laya.Sprite;

  private elementsList: Array<IElmentRoot>;

  initScene(options: any): void {
    this.stage = options.stage;
    this.elementsList = new Array();
    //this.elementsList=GameManager.getResolve("IDictionary");
    //this.elementsList.set(LayerEnum.backgroud,this.stage);
  }

  destroy(): void {
    while (this.elementsList.length > 0) {
      this.elementsList.pop().destroy(true);
    }
  }

  removeSprite(sprite: IElmentRoot) {
    var index = this.elementsList.indexOf(sprite);
    if (index > -1) {
      this.elementsList.splice(index, 1);
    }
  }
  addElementToLayer(sprite: IElmentRoot, posX?: number, posY?: number) {
    this.elementsList.push(sprite);
    this.addToLayer(sprite.spriteBase, sprite.layer, posX, posY);
  }

  getSceneSprite() {
    return this.stage;
  }
  getElmentList(): IElmentRoot[] {
    return this.elementsList;
  }
  addToLayer(
    sprite: Laya.Sprite,
    layer: LayerEnum,
    posX?: number,
    posY?: number
  ) {
    sprite.zOrder = layer;
    sprite.pos(posX, posY);
    this.stage.addChild(sprite);
  }
  update(): void {
    for (let i = 0; i < this.elementsList.length; i++) {
      const element = this.elementsList[i];
      if (element.isDead) {
        this.elementsList.splice(i, 1);
        i--;
      }
      this.beforeUpdate && this.beforeUpdate.runWith(element);
      element.update();
      this.updated && this.updated.runWith(element);
    }
  }
}
